<template>
  <div class="finance-submenu">
    
    <!-- 新增收款对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '收款信息的编辑' : '新增收款记录'"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="客户名称" prop="customerId">
          <el-select v-model="addForm.customerId" placeholder="请选择客户">
             
        <el-option label="客户1" :value=1 />
        <el-option label="客户2" :value=2 />
      
          </el-select>
        </el-form-item>
        <el-form-item label="应收金额" prop="receiptAmount">
          <el-input-number
            v-model="addForm.receiptAmount"
            :precision="2"
            :step="0.1"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="收款账户" prop="receiptAccount">
          <el-select v-model="addForm.receiptAccount" placeholder="请选择收款账户">
            <el-option
              v-for="item in bankOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否开票" prop="isInvoice">
          <el-radio-group v-model="addForm.isInvoice">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="预收日期" prop="advanceDate">
          <el-date-picker
            v-model="addForm.advanceDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="预收人" prop="advancePerson">
          <el-input v-model="addForm.advancePerson" placeholder="请输入预收人" />
        </el-form-item>
        <el-form-item label="关联项目" prop="relatedProject">
          <el-input v-model="addForm.relatedProject" placeholder="请输入关联项目" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="addForm.remarks"
            type="textarea"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.CustomenName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="是否开票" style="width: 180px;">
          <el-select v-model="searchForm.Isnoves" placeholder="请选择是否开票">
            <el-option :value="0" label="全部" />
            <el-option :value="1" label="已开票" />
            <el-option :value="2" label="未开票" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <div class="table-header">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="id" label="ID" width="80" v-if="false" />
        <el-table-column prop="customerName" label="客户名称" width="180" />
        <el-table-column prop="receiptAmount" label="应收金额" width="120" />
        <el-table-column prop="receiptAccount" label="收款账户" width="120" />
        <el-table-column prop="isInvoice" label="是否开票" width="120">
          <template #default="scope">
            {{ scope.row.isInvoice === 1 ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="advanceDate" label="预收日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.advanceDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="advancePerson" label="预收人" width="120" />
        <el-table-column prop="relatedProject" label="关联项目" width="120" />
        <el-table-column prop="remarks" label="备注" width="120" />
        <el-table-column prop="createName" label="创建人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateName" label="修改人" width="120" />
        <el-table-column prop="updateTime" label="修改时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[50, 100, 200, 300, 400]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import type { FormInstance, FormRules } from 'element-plus'
import read from '@/stores/host'


// 搜索表单数据
const searchForm = reactive({
  CustomenName: '',
  Isnoves: 0,
  index: 1,
  size: 50
})

// 表格数据
const tableData = ref([])

// 获取数据的方法
const fetchData = async () => {
  try {
    const response = await axios.get('http://localhost:5047/api/Management/GetResceive', {
      params: searchForm
    })
    if (response.data.code === 200) {
      console.log('获取到的数据：', response.data.data.data) // 添加日志查看数据结构
      tableData.value = response.data.data.data
      total.value = response.data.data.totalcount
    } else {
      showError(response.data.message || '获取数据失败')
    }
  } catch (error) {
    showError('网络请求失败，请稍后重试')
    console.error('获取数据失败：', error)
  }
}



// 在组件挂载时获取数据
onMounted(() => {
  fetchData()
 
})

import { ElMessage, ElMessageBox } from 'element-plus'

// 错误提示
const showError = (message: string) => {
  ElMessage.error(message)
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

// 格式化日期时间
const formatDateTime = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 分页相关
const currentPage = ref(1)
const pageSize = ref(50)
const total = ref(7)

// 搜索方法
const onSearch = () => {
  searchForm.index = 1
  fetchData()
}

// 分页方法
const handleSizeChange = (val: number) => {
  searchForm.size = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  searchForm.index = val
  fetchData()
}

// 编辑状态标记
const isEdit = ref(false)

// 操作方法
const handleDetail = (row: any) => {
  console.log('查看详情', row)
}

const handleEdit = (row: any) => {
  isEdit.value = true
  dialogVisible.value = true
  // 填充表单数据
  Object.assign(addForm, {
    id: row.id,
    customerId: row.customerId,
    receiptAmount: row.receiptAmount,
    receiptAccount: row.receiptAccount,
    isInvoice: row.isInvoice,
    advanceDate: row.advanceDate,
    advancePerson: row.advancePerson,
    relatedProject: row.relatedProject,
    remarks: row.remarks
  })
  console.log('编辑表单数据：', addForm) // 添加日志以便调试
}

// 银行账户选项
const bankOptions = [
  { value: '中国工商银行', label: '中国工商银行' },
  { value: '中国建设银行', label: '中国建设银行' },
  { value: '中国农业银行', label: '中国农业银行' },
  { value: '中国银行', label: '中国银行' },
  { value: '交通银行', label: '交通银行' }
]

// 新增表单数据
const addForm = reactive({
  id: 0,
  customerId: '',
  receiptAmount: 0,
  receiptAccount: '',
  isInvoice: 1,
  advanceDate: '',
  advancePerson: '',
  relatedProject: '',
  remarks: ''
})

// 表单验证规则
const rules = reactive<FormRules>({
  customerId: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
  receiptAmount: [{ required: true, message: '请输入应收金额', trigger: 'blur' }],
  receiptAccount: [{ required: true, message: '请输入收款账户', trigger: 'blur' }],
  isInvoice: [{ required: true, message: '请选择是否开票', trigger: 'change' }],
  advanceDate: [{ required: true, message: '请选择预收日期', trigger: 'change' }],
  advancePerson: [{ required: true, message: '请输入预收人', trigger: 'blur' }]
})

// 新增方法
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  // 重置表单数据
  Object.assign(addForm, {
    customerId: '',
    receiptAmount: 0,
    receiptAccount: '',
    isInvoice: 1,
    advanceDate: '',
    advancePerson: '',
    relatedProject: '',
    remarks: '',
    id: 0
  })
}

// 提交表单
const submitForm = async () => {
  if (!addFormRef.value) return
  
  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = isEdit.value 
          ? 'http://localhost:5201/api/Management/UpdataReceive'
          : 'http://localhost:5201/api/Management/AddReceive'
        
        console.log('提交的表单数据：', addForm) // 添加日志查看提交的数据
        const response = await axios.post(url, addForm)
        console.log('服务器响应：', response.data) // 添加日志查看服务器响应
        
        if (response.data.code === 200) {
          ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
          dialogVisible.value = false
          fetchData() // 刷新列表数据
        } else {
          showError(response.data.message || (isEdit.value ? '修改失败' : '添加失败'))
        }
      } catch (error) {
        showError('网络请求失败，请稍后重试')
        console.error(isEdit.value ? '修改失败：' : '添加失败：', error)
      }
    }
  })
}

// 对话框相关
const dialogVisible = ref(false)
const addFormRef = ref<FormInstance>()

// 删除方法
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认要删除这条收款记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.post('http://localhost:5201/api/Management/DelLoginReceive', { id: row.id })
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchData() // 刷新列表数据
    } else {
      showError(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      showError('删除失败，请稍后重试')
      console.error('删除失败：', error)
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  padding: 20px 0 0;
  text-align: right;
}

.finance-submenu {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.table-header {
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>